package anveshitha.servlets;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import de.java2html.converter.JavaSource2HTMLConverter;
import de.java2html.javasource.JavaSource;
import de.java2html.javasource.JavaSourceParser;
import de.java2html.options.JavaSourceConversionOptions;



/**
 * Servlet implementation class for Servlet: GetCodeHtmlServlet
 *
 */
 public class GetCodeHtmlServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private static Logger log = Logger.getLogger(GetCodeHtmlServlet.class);
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public GetCodeHtmlServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html");

		//get the file path
		String filepath = request.getParameter("file");
		
		//check for file consistency
		try{
			File file = new File(filepath);
			if(!file.exists() || !file.isFile()){
				throw new FileNotFoundException("File Not Found!!");
			}
		
		//TODO: move this code to a separate class
		JavaSource source = new JavaSourceParser().parse(new FileReader(filepath));
		
		//converter options
		JavaSourceConversionOptions options = JavaSourceConversionOptions.getDefault();
		options.setShowLineNumbers(true);
		options.setShowFileName(true);

		//Create a converter and write the JavaSource object as Html
		JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter();
		OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
		
		//write headers
		writer.write("<html><head></head><body>");

	    converter.convert(source,options,writer);
		
	    //write footers
	    writer.write("</body></html>");

		}catch(IOException ioe){
			log.error("IOException: "+ioe.getMessage());
			response.sendError(404,"Error occured while reading file!!");
		}

		//response.flushBuffer();
	}   	  	    
}